package flyshoes.filters;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import flyshoes.config.ExcludePathConfig;
import flyshoes.utils.JwtUtil;

import java.util.List;

@Component
@RequiredArgsConstructor
//登录拦截
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final ExcludePathConfig excludePathConfig;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    private final StringRedisTemplate stringRedisTemplate;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request
        ServerHttpRequest request = exchange.getRequest();
        //2.判断是否做登录拦截
        if (isExclude(request.getPath().toString())) {
            //放行
            return chain.filter(exchange);
        }
        //3.获取token
        String token = null;
        List<String> headers = request.getHeaders().get("Authorization");
        if (headers != null && !headers.isEmpty()) {
            token = headers.get(0);
            System.out.println("现在的token是：：：" + token);

        } else {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            System.out.println("缺少Authorization");
            return response.setComplete();
        }
        Integer userId = null;
        //从redis中获取token,实现令牌主动失效
        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
        String tokenKey = "token:" + token;


        //4.校验并解析token
        try {
            String redisToken = stringStringValueOperations.get(tokenKey);
            if (redisToken != null) {
                System.out.println("现在的redisToken是：" + redisToken);
                userId = JwtUtil.parseToken(token);
                System.out.println("现在UserID是：" + userId);
            }else {
                System.out.println("token已失效");
            }
        } catch (WebClientResponseException.Unauthorized e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        //5.传递用户信息
        String userInfo = userId.toString();
        ServerWebExchange serverWebExchange = exchange.mutate().request(builder -> builder.header("user-info", userInfo)).build();
        //6.放行
        return chain.filter(serverWebExchange);
    }

    //判断路径是否匹配
    private boolean isExclude(String path) {
        for (String excludePath : excludePathConfig.getExcludePaths()) {
            if (antPathMatcher.match(excludePath, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
